<template>
  <div class="plant">
    <header>
      <BaseNavBar title="添加帖子" :is-nav="true" />
    </header>
    <main style="margin-top: 8px;">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field label="图片">
            <template #input>
              <SingleUploader @upload-success="(value) => {
                post.cover = `/api${value}`;
              }" />
            </template>
          </van-field>
          <van-field v-model="post.nickname" name="title" label="标题" placeholder="请输入标题" />
          <van-field v-model="post.variety" name="content" label="内容" placeholder="请输入帖子内容" />
          <van-field v-model="post.tag" name="tag" label="标签" placeholder="请输入帖子标签" />
          <van-field v-model="post.plateName" name="plateId" label="帖子板块" placeholder="请选择帖子板块"
            @click="show = true" />
        </van-cell-group>

        <div style="margin: 16px;">
          <van-button round block type="primary" color="#4A90E2" native-type="submit">
            确定
          </van-button>
          <van-button style="margin-top: 8px;" round block type="primary" plain color="#4A90E2" @click="handleReset">
            重置
          </van-button>
        </div>
      </van-form>
      <van-popup v-model:show="show" position="bottom" :style="{ height: '40%', backgroundColor: '#fff' }">
        <van-date-picker :columns="columns" title="请选择帖子板块" @confirm="handleConfirm" @cancel="show = false" />
      </van-popup>
    </main>

  </div>
</template>

<script setup>
import { ref,onMounted} from 'vue';
import { showToast} from 'vant';
import SingleUploader from '@/components/SingleUploader/index.vue';
import BaseNavBar from '@/components/BaseNavBar/index.vue';
import { getPlateLabel } from '@/apis/plate';
import { addPost} from '@/apis/post'


const columns = ref([]);
const post = ref({
  plateId: "",
  title:"",
  content:"",
  tag:"",
  cover: "",
  plateName:"",
});
const show = ref(false);
const handleConfirm = (option) => {

  post.value.plateId = option?.selectedOptions?.[0]?.value;
  post.value.plateName = option?.selectedOptions?.[0]?.text;
  show.value = false;
};
const onSubmit = async (values) => {

  try {
        const { code, msg } = await addPost ({...values,cover:post.value.cover,status:1,plateId:post.value.plateId});
        if (code === 200) {
          showToast('添加成功');
          return
        }
        showToast(msg);

      } catch (error) {
        console.log(error, 'error');

      }
};
const handleReset = () => {
  post.value = {};
};

const init = async () => {
  try {
    const res = await getPlateLabel();
    columns.value = res?.data?.map(item=>{
      return {
        text: item?.label,
        value: item?.value
      }
    })

  } catch (error) {
    console.log(error, 'get-plate-error');

  }
};

onMounted(() => {
  init();
});
</script>

<style lang="less" scoped>
</style>
